/**
 * 对象数组深拷贝
 * @param {Array,Object} source 需要深拷贝的对象数组
 * @param {Array} noClone 不需要深拷贝的属性集合
 */
export function deepClone(source, noClone = []) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object' && noClone.indexOf(keys) === -1) {
      targetObj[keys] = deepClone(source[keys], noClone)
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}
// 用于格式化时间
export function formatDate(value, format) {
  //value: 需要格式化的数据
  //format: 指定格式  v hh:mm:ss

  let date = new Date(value)
  // 获取年份
  let year = date.getFullYear()

  if (/(y+)/.test(format)) {
    // 获取匹配组的内容
    let content = RegExp.$1
    format = format.replace(content, year.toString().slice(4 - content.length))
  }

  let o = {
    // y: date.getFullYear(),  // 用这一句也行，但只适用于四位数显示时候用
    M: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    m: date.getMinutes(),
    s: date.getSeconds()
  }

  for (let key in o) {
    // 构造动态正则
    let reg = new RegExp(`(${key}+)`)

    if (reg.test(format)) {
      // 获取匹配组的内容
      let content = RegExp.$1
      let k = o[key] >= 10 ? o[key] : content.length == 2 ? '0' + o[key] : o[key]
      format = format.replace(content, k)
    }
  }
  return format
}

export const getCookie = (cname) => {
  var name = cname + '='
  var ca = document.cookie.split(';')
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i]
    while (c.charAt(0) === ' ') c = c.substring(1)
    if (c.indexOf(name) !== -1) return c.substring(name.length, c.length)
  }
  return ''
}
// 数组排序
export const compareArr = (keyName) => {
  return function(obj1, obj2) {
    var val1 = obj1[keyName]
    var val2 = obj2[keyName]
    if (val1 < val2) {
      return -1
    } else if (val1 > val2) {
      return 1
    } else {
      return 0
    }
  }
}
export function getArrayLength(arr = []) {
  let length = arr.length
  arr.forEach((item) => {
    if (Array.isArray(item.children)) {
      length += getArrayLength(item.children)
    }
  })
  return length
}
